<template>
  <div class="uploadWord">
    <div class="img-wrapper" @click="uploadHandle" v-show="!fileName">
      <i class="el-icon-plus icon" ></i>
      <el-progress type="circle" :percentage="percentage" class="progress" v-show="percentShow"></el-progress>
      <div class="shade"></div>
      <input type="file" ref="inputfile" @change="fileChangeHandle" style="display: none;">
    </div>
    <div v-show="fileName" class="file-card" @click='uploadHandle'>
        <div class="left-text">
            <span>{{fileName}}</span>
        </div>
        <el-button class="el-icon-refresh" style="float: right; padding: 3px 0" type="text" ></el-button>
    </div>

   
  </div>
    
</template>

<script>
  import * as qiniu from 'qiniu-js'
  import api from '@/api/apiPath'
  import Util from '../../../common/utils'
  export default {
    name: "upload-excel",
    data () {
      return {
        percentage: 0,
        percentShow: false,
        token: '',
        qiniuUrl: '',
        fileName:'',
        fileUrl:'',
        isChange:false,//是否选取文件
      }
    },
    props: ['name','url'],
    created () {
        this.fileName = this.name|| '';
        this.fileUrl = this.url|| '';
        this.axios.post(api.UPLOADTOKEN, {}).then(res => {
            this.token = res.data.data.imgToken
            this.qiniuUrl = res.data.data.qiniuUrl
      })
    },
    watch: {
      name (val) {
        this.fileName = this.name|| '';
        this.fileUrl = this.url|| '';
      }
    },
    methods: {
      uploadHandle () {
        const node = this.$refs.inputfile
        node.click()
      },
      fileChangeHandle () {
        const file = this.$refs.inputfile.files[0]
        // 判断文件类型
        if(!file) {
          this.reset();
          return false;
        };
        const upType = ['doc','docx']
        const fileName = file.name
        const postfix = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)
        const fileSize = (file.size / 1024).toFixed(0); 
        const maxNun = (this.fileSize / 1024).toFixed(0); 
        if (!upType.includes(postfix)) {
            this.$alert('只支持doc docx格式的文件', '提示', {
                    type: 'error',
                    confirmButtonText: '确定',
                    callback: action => {
                        }
            });
          return false
        }
        if(fileSize>this.fileSize){
          this.$alert(`上传文件不能大于${maxNun}M`, '提示', {
                    type: 'error',
                    confirmButtonText: '确定',
                    callback: action => {
                        }
            });
            return false
        }
        this.fileName = fileName;
        this.isChange = true;
        return true;
      },
      // 用七牛上传
      uploadQiniu () {
        //编辑状态并且未发生文件更换
        if(this.name && this.url && !this.isChange){
            this.$emit('uploadSuccess',{fileName:this.name,fileUrl:this.url});
            return;
        }
        const file = this.$refs.inputfile.files[0];
        if(!file || !this.fileChangeHandle()) {
          this.$alert("请上传附件", '提示', {
                confirmButtonText: '确定',
                callback: action => {
                }
            });
          return;
        }
        const fileName = file.name
        const postfix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
        const name = Util.getTimeString2(new Date().getTime())
        const token = this.token
        var putExtra = {
          fname: fileName,
          params: {},
          mimeType: null
        }
        var config = {
          useCdnDomain: true
        }
        var observable = qiniu.upload(file, fileName, token, putExtra, config)
        const vueThis = this
        this.percentShow = true
        this.percentage = 10
        observable.subscribe(function (res) {
          console.log('上传进度：', res)
          vueThis.percentage = res.total.percent
        }, function (error) {
          console.error('上传失败：', error)
        }, function (res) {
          vueThis.percentShow = false
          vueThis.fileUrl = vueThis.qiniuUrl + res.key
          vueThis.$emit('uploadSuccess', {fileName:fileName,fileUrl:vueThis.fileUrl})
        })
      },
      reset(){
          this.fileName = '';
          this.fileUrl = '';
          this.$refs.inputfile.value = '';
      }
    }
  }
</script>

<style lang="stylus" scoped>
  .important{
      color: #f56c6c;
      margin-right: 4px;
  }
  .uploadWord{
      display :flex;
      align-items: center;
     
    .img-wrapper{
      position: relative;
      width: 240px;
      height: 40px;
      background-color: #fbfdff;
      border: 1px dashed #c0ccda;
      border-radius: 6px;
      box-sizing: border-box;
      cursor: pointer;
      overflow: hidden;
      &:hover{
        border-color: #409eff;
        color: #409eff;
        .shade{
          display: block;
        }
        .icon{
          color: #fff;
          z-index: 9;
        }
      }
      .shade{
        position: absolute;
        display: none;
        background: rgba(0,0,0,0.5);
        left: 0;
        top: 0;
        right:0;
        bottom: 0;
      }
      .icon{
        font-size: 26px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
      .imgNode{
        width: 148px;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
      }
      .progress{
        margin-top: 10px;
        margin-left: 10px;
      }
    }
    .file-card{
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
        min-width: 250px;
        align-items: center;
        display: flex;
        padding:0 10px;
         cursor: pointer;

        .left-text{
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        button{
            padding:0 15px;
        }
    }
    
  }
</style>
